package com.aacar.utils.pinyin;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class PinyinUtil {

	// 分词正则表达式
	public static String regEx = "[^aoeiuv]?h?[iuv]?(ai|ei|ao|ou|er|ang?|eng?|ong|a|o|e|i|u|ng|n)?";

	public static String split(String input) {
		int tag = 0;
		StringBuffer sb = new StringBuffer();
		String formatted = "";
		List<String> tokenResult = new ArrayList<String>();
		for (int i = input.length(); i > 0; i = i - tag) {
			Pattern pat = Pattern.compile(regEx);
			Matcher matcher = pat.matcher(input);
			boolean rs = matcher.find();
			sb.append(matcher.group());
			sb.append("\'");
			tag = matcher.end() - matcher.start();
			tokenResult.add(input.substring(0, 1));
			input = input.substring(tag);
		}
		if (sb.length() > 0) {
			formatted = sb.toString().substring(0, sb.toString().length() - 1);
		}
		return formatted;
	}
	
	// 判断是否都是汉字
	public static boolean isAllHanzi(String str){
		HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        
        boolean isAllHanzi = true;
        
		for(int i = 0; i < str.length(); ++i) {
			String[] pinyin = null;
			try {
	            pinyin = PinyinHelper.toHanyuPinyinStringArray(str.charAt(i), format);
	        } catch(BadHanyuPinyinOutputFormatCombination e) {
	            e.printStackTrace();
	        }
			
			// 是汉字
			if(pinyin == null){
				isAllHanzi = false;
			}
		}
		
		return isAllHanzi;
	}

	public static void main(String[] args) {
		String str = "beijing";
		System.out.println(PinyinUtil.split(str));
		
		Chinese chinese = new Chinese();
		
		StringBuilder mid = new StringBuilder();
		
		String[] cPinyin = chinese.getStringPinYin(PinyinUtil.split("gn2")).split("'");
		for(String cc: cPinyin){
			mid.append(cc).append("*[a-z]'");
		}
		
		String cityPinyin = mid.toString().substring(0, mid.lastIndexOf("'"));
		
		System.out.println(cityPinyin);
		
	}
}
